﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace System.Web.Mvc
{
    public static class ViewToStringRenderer
    {
        public static string RenderPartialViewToString(this Controller controller, string viewName)
        {
            return RenderPartialViewToString(controller.ControllerContext, viewName, null);
        }

        public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
        {
            return RenderPartialViewToString(controller.ControllerContext, viewName, model);
        }

        private static string RenderPartialViewToString(ControllerContext controllerContext, string viewName, object model)
        {
            if (controllerContext == null)
                controllerContext = new ControllerContext();

            if (string.IsNullOrEmpty(viewName))
                viewName = controllerContext.RouteData.GetRequiredString("action");

            controllerContext.Controller.ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

    }
}
